package model

import (
	"github.com/tianjigames/fairy/constants"
	"github.com/tianjigames/fairy/util"
	"github.com/topfreegames/pitaya/logger"
)

type SkillData struct {
	MVersion byte //数据版本
	SkillList []int //角色所拥有的所有技能id
	EquipSkillList []int //角色可装备的最大技能数
	GangSkillRange []int //帮会技能在skillList中的下标范围
	GangSkillLength int //帮会技能长度
}

func NewSkillData() *SkillData {
	return &SkillData{
		SkillList: make([]int,constants.MaxSkillNum),
		EquipSkillList: make([]int,constants.MaxEquipativeSkillNum),
		GangSkillRange: []int{6110100,6110200,6110300,6110400,6110500,6110600,6110700,6110800},
		GangSkillLength: 10,
	}
}

/**
反序列化对象
 */
func UnSerializeSkillData(data []byte) *SkillData {
	newMData := NewSkillData()
	if data != nil && len(data) > 0 {
		newMData.ReadObject(data)
	}
	
	return newMData
}

func (p *SkillData) ReadObject(in []byte) {
	nBeginIdx := 0
	p.MVersion = in[nBeginIdx]
	nBeginIdx ++
	if p.MVersion == 0 {
		//读取玩家所有技能数组
		nSize := constants.MaxSkillNum*4
		util.ByteArrayToIntArray(in,nBeginIdx,nSize,p.SkillList,0)
		nBeginIdx += nSize

		//读取玩家装备的技能数组
		nSize = constants.MaxEquipativeSkillNum*4
		util.ByteArrayToIntArray(in,nBeginIdx,nSize,p.EquipSkillList,0)
		nBeginIdx += nSize
	}
}

/**
修改重复的帮会技能 新的帮会技能替换老的帮会技能
 */
func (p *SkillData) GangSkillRepairModel(guid int64)  {
	if p.GangSkillRange == nil || p.GangSkillLength == 0 {
		return
	}

	const mark = -999
	needRepair := false
	flag := make([]int,len(p.GangSkillRange))
	for i := 1;i<= p.SkillList[0];i++ {
		if p.SkillList[i] >= p.GangSkillRange[0] && p.SkillList[i] <= p.GangSkillRange[len(p.GangSkillRange) - 1] + p.GangSkillLength {
			tag := (p.SkillList[i] - p.GangSkillRange[0])/100
			if flag[tag] == 0 {
				flag[tag] = i
				continue
			}

			needRepair = true
			if p.SkillList[flag[tag]] < p.SkillList[i] { //帮会有新技能
				logger.Log.Infof("gangSkillRepairModel guid:%d,old:%d,new:%d",guid,p.SkillList[flag[tag]],p.SkillList[i])
				p.SkillList[flag[tag]] = mark
				flag[tag] = i
			} else{
				logger.Log.Infof("gangSkillRepairModel guid:%d,old:%d,new:%d",guid,p.SkillList[i],p.SkillList[flag[tag]])
				p.SkillList[i] = mark
			}
		}
	}

	if needRepair {
		tempSkill := make([]int,constants.MaxSkillNum)
		for i:=1;i<=p.SkillList[0];i++ {
			if p.SkillList[i] == mark {
				continue
			}

			tempSkill[0] += 1
			tempSkill[i] = p.SkillList[i]
		}
		p.SkillList = tempSkill
	}
}

/**
获取技能的数量
 */
func (p *SkillData) GetSkillNum() int {
	return p.SkillList[0]
}


